package com.clj.blesample;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;

import com.blankj.utilcode.util.AdaptScreenUtils;
import com.clj.blesample.compose.BaseEmptyTransformer;
import com.clj.blesample.databinding.ActivityRecordBinding;
import com.clj.blesample.entity.AppConstant;
import com.clj.blesample.entity.Record;
import com.clj.blesample.entity.Result;
import com.clj.blesample.http.retrofit.RetrofitManager;
import com.clj.blesample.menu.ChangeIpActivity;
import com.clj.blesample.menu.ErrorUploadActivity;
import com.clj.blesample.menu.RecordListActivity;
import com.clj.blesample.udp.UdpClient;
import com.clj.blesample.utils.GpsUtil;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleMtuChangedCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.HexUtil;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tendcloud.tenddata.TalkingDataSDK;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class CollectActivity extends AppCompatActivity implements View.OnClickListener, OnChartValueSelectedListener, UdpClient.OnDataReceiveListener {
    private ActivityRecordBinding mBinding;
    private ProgressDialog mProgressDialog;
    private ProgressDialog mUploadProgressDialog;
    private BleDevice mBleDevice;
    private BluetoothGattService mConnectService;
    private BluetoothGattCharacteristic mWriteCharacteristic;
    private BluetoothGattCharacteristic mNotifyCharacteristic;
    private List<Record> mRecords = new ArrayList<>();
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //    private StringBuffer endSb = new StringBuffer();
    private StringBuffer endSb = new StringBuffer();
    private String mEndData = "";
    private boolean isStartUdp = false;
    private ExecutorService sendUdpService = Executors.newSingleThreadExecutor();
    private ExecutorService uploadService = Executors.newSingleThreadExecutor();
    private DecimalFormat format = new DecimalFormat("#.00");
    private boolean isReceiveEndData = true;
    private int writeCount = 0;
    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
    private static final int REQUEST_CODE_OPEN_GPS = 1;

    //HR相关UUID
    //    private final String SERVICE_UUID = "0000ffa0-0000-1000-8000-00805f9b34fb";
//    private final String NOTIFY_UUID = "0000ffa1-0000-1000-8000-00805f9b34fb";
//    private final String WRITE_UUID = "0000ffa1-0000-1000-8000-00805f9b34fb";
    //HC相关UUID
//    private final String SERVICE_UUID = "0000ffe0-0000-1000-8000-00805f9b34fb";
//    private final String NOTIFY_UUID = "0000ffe1-0000-1000-8000-00805f9b34fb";
//    private final String WRITE_UUID = "0000ffe2-0000-1000-8000-00805f9b34fb";
    private final Handler mHandler = new Handler(Looper.getMainLooper());
    private boolean isHRDevice = false;
    private Disposable mWriteDisposable;
    private boolean isUdpSending = false;
    private Map<String, String> historyData = new HashMap<>();
    private BleNotifyCallback clearNotifyCallback;
    private LocationManager mLocationManager;
    private final LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(@NonNull Location location) {
            if (location.getLatitude() > 0 && location.getLongitude() > 0) {
                AppConstant.mLatitude = location.getLatitude();
                AppConstant.mLongitude = location.getLongitude();
            }
            log("获取到经纬度：" + AppConstant.mLatitude + "----" + AppConstant.mLongitude);
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        mBinding = ActivityRecordBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());
        //初始化表格
        initChart();
        //连接udp
        connectUdp();
        mBinding.llConnectBle.setOnClickListener(this);
        mBinding.tvStartCollect.setOnClickListener(this);
        mBinding.tvClearHistory.setOnClickListener(this);
        mBinding.tvEndAll.setOnClickListener(this);
        mBinding.tvTitle.setOnClickListener(this);
        mBinding.tvWelcome.setOnClickListener(this);
        mBinding.llErrorUpload.setOnClickListener(this);
        mBinding.llQueryRecord.setOnClickListener(this);
        mBinding.ivMenu.setOnClickListener(this);
        mBinding.llChangeIp.setOnClickListener(this);
        checkPermissions();
    }

    @Override
    protected void onResume() {
        super.onResume();
        TalkingDataSDK.onPageBegin(this, getClass().getName());
    }

    @Override
    protected void onPause() {
        super.onPause();
        TalkingDataSDK.onPageEnd(this, getClass().getName());
    }

    @Override
    public Resources getResources() {
        return AdaptScreenUtils.adaptWidth(super.getResources(), 375);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1000 && resultCode == RESULT_OK && data != null) {
            mBleDevice = data.getParcelableExtra("data");
            connectBle(mBleDevice);
        } else {
            if (requestCode == REQUEST_CODE_OPEN_GPS) {
                if (checkGPSIsOpen()) {
                    getLocation();
                }
            }
        }
    }

    /**
     * 连接蓝牙
     *
     * @param bleDevice
     */
    private void connectBle(BleDevice bleDevice) {
        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                showProgress("正在连接蓝牙...");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                hideProgress();
                hideClearProgress();
                Toast.makeText(CollectActivity.this, getString(R.string.connect_fail), Toast.LENGTH_SHORT).show();
                resetBleData();
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                hideProgress();
                initBleData();
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
                hideProgress();
                hideClearProgress();
                Toast.makeText(CollectActivity.this, getString(R.string.disconnected), Toast.LENGTH_SHORT).show();
                resetBleData();
            }
        });
    }

    /**
     * 开始采集
     */
    private void startCollect() {
        if (mBleDevice == null || mConnectService == null || mNotifyCharacteristic == null) {
            Toast.makeText(this, "蓝牙未连接", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            mBinding.tvStartCollect.setText("正在采集...");
            mBinding.tvStartCollect.setEnabled(false);
            //开始接收蓝牙广播数据
            isReceiveEndData = false;
            mRecords.clear();
            showChartData(new ArrayList<Record>());
            mEndData = "";
            endSb = new StringBuffer();
            mBinding.tvCollectState.setText(R.string.collecting);
            startNotify();
        } catch (Exception e) {
            log("开始采集时出现异常：" + Log.getStackTraceString(e));
            Toast.makeText(CollectActivity.this, "出现异常，请重试", Toast.LENGTH_SHORT).show();
            resetBleData();
        }

    }

    /**
     * 开始循环发送获取电流电压指令
     */
    private void startLoopWrite() {
        if (mWriteDisposable != null && !mWriteDisposable.isDisposed()) {
            mWriteDisposable.dispose();
        }
        mWriteDisposable = Observable.interval(1, 1, TimeUnit.SECONDS)
                .observeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        writeEvCode();
                    }
                });
    }

    /**
     * 写入获取电流电压指令
     */
    private void writeEvCode() {
        if (isReceiveEndData) {
            log("定时发送已停止");
            stopLoopWrite();
        } else {
            writeCount++;
            BleManager.getInstance().write(
                    mBleDevice,
                    mWriteCharacteristic.getService().getUuid().toString(),
                    mWriteCharacteristic.getUuid().toString(),
                    HexUtil.hexStringToBytes("01030076000225D1"),
                    new BleWriteCallback() {

                        @Override
                        public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                            log("写入获取电流指令成功: " + HexUtil.formatHexString(justWrite, true));
                            writeCount--;
                        }

                        @Override
                        public void onWriteFailure(final BleException exception) {
                            log("写入获取电流指令异常：" + exception.toString() + "--" + System.currentTimeMillis());
                            writeCount--;
                        }
                    });
        }
    }

    /**
     * 结束循环发送获取电流电压指令
     */
    private void stopLoopWrite() {
        if (mWriteDisposable != null && !mWriteDisposable.isDisposed()) {
            mWriteDisposable.dispose();
        }
        mWriteDisposable = null;
    }

    /**
     * 重置当前页面数据
     */
    private void resetBleData() {
        try {
            //终止接收notify
            isReceiveEndData = true;
            isStartUdp = false;
            mConnectService = null;
            mNotifyCharacteristic = null;
            mWriteCharacteristic = null;
            mBinding.tvBleState.setText(R.string.unconnect);
            mBinding.tvCollectState.setText(R.string.uncollect);
            mBinding.tvStartCollect.setText("正在重置数据");
            mBinding.tvStartCollect.setEnabled(false);
            mBinding.tvClearHistory.setEnabled(false);
            mRecords.clear();
            if (mBleDevice != null) {
                BleManager.getInstance().disconnect(mBleDevice);
            }
            BleManager.getInstance().disconnectAllDevice();
            stopLoopWrite();
            stopNotify();
            mBleDevice = null;
            showChartData(new ArrayList<Record>());
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mBinding.tvStartCollect.setText(R.string.start_collect);
                    mBinding.tvStartCollect.setEnabled(true);
                    mBinding.tvClearHistory.setEnabled(true);
                }
            }, 2000L);
        } catch (Exception e) {
            log("出现异常：" + Log.getStackTraceString(e));
        }

    }

    private void connectUdp() {
        UdpClient.getInstance().setOnDataReceiveListener(this);
        UdpClient.getInstance().connect(AppConstant.getIP(), Integer.parseInt(AppConstant.getPort()));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        stopLoopWrite();
        mHandler.removeCallbacksAndMessages(null);
        if (mBleDevice != null) {
            //断开蓝牙连接
            BleManager.getInstance().disconnect(mBleDevice);
        }
        BleManager.getInstance().disconnectAllDevice();
        BleManager.getInstance().destroy();
        if (mLocationManager != null) {
            mLocationManager.removeUpdates(locationListener);
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tvTitle) {
            if (mBinding.svLog.getVisibility() == View.VISIBLE) {
                mBinding.svLog.setVisibility(View.GONE);
            } else {
                mBinding.svLog.setVisibility(View.VISIBLE);
            }
        }
        if (id == R.id.llConnectBle) {
            if (mBinding.tvBleState.getText().toString().equals(getString(R.string.connected))) {
                Toast.makeText(this, R.string.connected, Toast.LENGTH_SHORT).show();
                return;
            }
            //连接蓝牙
            startActivityForResult(new Intent(this, ScanBleActivity.class), 1000);
        }
        if (id == R.id.tvEndAll) {
            resetBleData();
//            mEndData = "14 80 20 20 20 20 00 00 00 15 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 39 35 32 34 30 34 33 32 30 36 33 33 39 39 32 30 33 33 30 38 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 20 20 20 21 20 20 20 43 6F 75 6F 6C 65 72 20 20 44 44 00 3F 00 00 00 00 64 00 E0 00 01 8B 01 8B 00 50 00 0F 03 84 00 00 00 7A 1E 35 01 18 11 05 00 00 00 00 00 00 00 00 00 00 2A FF".replace(" ", "");
//            sendUdp();
        }
        if (id == R.id.tvStartCollect) {
            if (!mBinding.tvClearHistory.isEnabled()) {
                return;
            }
            //开始采集
            startCollect();
        }
        if (id == R.id.tvClearHistory) {
            //上传历史数据
            if (!mBinding.tvStartCollect.isEnabled()) {
                return;
            }

            if (mBleDevice == null || mConnectService == null || mNotifyCharacteristic == null) {
                Toast.makeText(this, "蓝牙未连接", Toast.LENGTH_SHORT).show();
                return;
            }
            stopNotify();
            showClearProgress("正在同步历史数据...");
            log("开始同步历史记录");
            mBinding.tvClearHistory.setEnabled(false);
            historyData.clear();
            resetClearHistory();
        }
        if (id == R.id.tvWelcome) {
            //清空日志
            mBinding.tvLog.setText("");
            Toast.makeText(this, "日志已清空", Toast.LENGTH_SHORT).show();
        }
        if (id == R.id.ivMenu) {
            //抽屉
            mBinding.drawerLayout.openDrawer(GravityCompat.END);
        }
        if (id == R.id.llErrorUpload) {
            //异常数据上传
            startActivity(new Intent(this, ErrorUploadActivity.class));
        }
        if (id == R.id.llQueryRecord) {
            //电熔数据查询
            startActivity(new Intent(this, RecordListActivity.class));
        }
        if (id == R.id.llChangeIp) {
            //修改服务器地址
            startActivity(new Intent(this, ChangeIpActivity.class));

        }
    }

    private void resetClearHistory() {
        isReceiveEndData = false;
        mEndData = "";
        endSb = new StringBuffer();
        isUdpSending = false;
        startClearHistoryNotify();
        log("开始计时15S");
        if (stopUploadHistory != null) {
            mHandler.removeCallbacks(stopUploadHistory);
            stopUploadHistory = null;
        }
        mHandler.postDelayed(stopUploadHistory = new Runnable() {
            @Override
            public void run() {
                stopNotify();
                if (stopUploadHistory != null) {
                    mHandler.removeCallbacks(stopUploadHistory);
                    stopUploadHistory = null;
                }
                mBinding.tvClearHistory.setEnabled(true);
                hideClearProgress();
                Toast.makeText(CollectActivity.this, "同步结束", Toast.LENGTH_SHORT).show();
                log("同步结束");
            }
        }, 15000L);
    }

    /**
     * 初始化表格
     */
    private void initChart() {
        LineChart chart = mBinding.chart;
        chart.setOnChartValueSelectedListener(this);

        // no description text
        chart.getDescription().setEnabled(false);

        // enable touch gestures
        chart.setTouchEnabled(true);

        chart.setDragDecelerationFrictionCoef(0.9f);
        chart.setNoDataText("暂无数据");
        chart.setNoDataTextColor(Color.BLACK);
        // enable scaling and dragging
        chart.setDragEnabled(true);
        chart.setScaleEnabled(true);
        chart.setDrawGridBackground(false);
        chart.setHighlightPerDragEnabled(true);

        // if disabled, scaling can be done on x- and y-axis separately
        chart.setPinchZoom(true);

        // set an alternative background color
        chart.setBackgroundColor(Color.WHITE);
        chart.animateX(200);

        // get the legend (only possible after setting data)
        Legend l = chart.getLegend();

        // modify the legend ...
        l.setForm(Legend.LegendForm.LINE);
        l.setTextSize(11f);
        l.setTextColor(Color.BLACK);
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
//        l.setYOffset(11f);

        XAxis xAxis = chart.getXAxis();
        xAxis.setTextSize(11f);
        xAxis.setAxisMinimum(0f);
        xAxis.setAxisMaximum(20f);
        xAxis.setTextColor(Color.BLACK);
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(false);

        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setTextColor(ColorTemplate.getHoloBlue());
        leftAxis.setAxisMaximum(70f);
        leftAxis.setAxisMinimum(0f);
        leftAxis.setDrawGridLines(true);
        leftAxis.setGranularityEnabled(true);

        YAxis rightAxis = chart.getAxisRight();
        rightAxis.setTextColor(Color.RED);
        rightAxis.setAxisMaximum(50f);
        rightAxis.setAxisMinimum(0f);
        rightAxis.setDrawGridLines(false);
        rightAxis.setDrawZeroLine(false);
        rightAxis.setGranularityEnabled(false);
        showChartData(new ArrayList<Record>());
    }

    public void initBleData() {
        if (mBleDevice == null) {
            String log = "蓝牙连接失败，未找到设备";
            log(log);
            Toast.makeText(this, log, Toast.LENGTH_SHORT).show();
            return;
        }
        String serviceUUID = getServiceUUID(mBleDevice);
        String notifyUUID = getNotifyUUID(mBleDevice);
        String writeUUID = getWriteUUID(mBleDevice);
        BluetoothGatt gatt = BleManager.getInstance().getBluetoothGatt(mBleDevice);

        for (BluetoothGattService service : gatt.getServices()) {
            if (service.getUuid().toString().equalsIgnoreCase(serviceUUID)) {
                mConnectService = service;
            }
        }
        if (mConnectService == null) {
            String log = "蓝牙连接失败，未找到对应" + serviceUUID + "的蓝牙服务";
            log(log);
            Toast.makeText(this, log, Toast.LENGTH_SHORT).show();
            return;
        }
        for (BluetoothGattCharacteristic characteristic : mConnectService.getCharacteristics()) {
            int charaProp = characteristic.getProperties();
            if (characteristic.getUuid().toString().equalsIgnoreCase(notifyUUID)) {
                if ((charaProp & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                    mNotifyCharacteristic = characteristic;
                }
            }
            if (characteristic.getUuid().toString().equalsIgnoreCase(writeUUID)) {
                if (((charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) > 0) || ((charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0)) {
                    mWriteCharacteristic = characteristic;
                }
            }
        }

        if (mNotifyCharacteristic == null) {
            String log = "蓝牙连接失败，未找到Notify特征:" + notifyUUID;
            log(log);
            Toast.makeText(this, log, Toast.LENGTH_SHORT).show();
            resetBleData();
            return;
        }
        if (mWriteCharacteristic == null) {
            String log = "蓝牙连接失败，未找到Write特征:" + writeUUID;
            log(log);
            Toast.makeText(this, log, Toast.LENGTH_SHORT).show();
            resetBleData();
            return;
        }
        isHRDevice = !TextUtils.isEmpty(mBleDevice.getName()) && mBleDevice.getName().toUpperCase().startsWith("HR");
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                BleManager.getInstance().setMtu(mBleDevice, 200, new BleMtuChangedCallback() {
                    @Override
                    public void onSetMTUFailure(BleException exception) {
                        log("mtu设置失败");
                        log("蓝牙连接失败");
                        resetBleData();
                    }

                    @Override
                    public void onMtuChanged(int mtu) {
                        log("mtu设置成功");
                        log("蓝牙连接成功");
                        Toast.makeText(CollectActivity.this, getString(R.string.ble_connected), Toast.LENGTH_SHORT).show();
                        mBinding.tvBleState.setText(R.string.connected);
                    }
                });
            }
        }, 300L);

    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        mBinding.chart.centerViewToAnimated(e.getX(), e.getY(),
                mBinding.chart.getData().getDataSetByIndex(h.getDataSetIndex())
                        .getAxisDependency(), 500);
    }

    @Override
    public void onNothingSelected() {

    }

    @Override
    public void onConnectSuccess() {
        log("udp连接成功");
    }

    @Override
    public void onConnectFail() {
        log("udp连接失败");
    }

    @Override
    public void onDataReceive(byte[] buffer, int size, int requestCode) {
        String endCode = HexUtil.formatHexString(buffer);
        if (requestCode == 1001) {
            isStartUdp = false;
            log("接收到udp数据1001：" + endCode);
            if (endCode.toLowerCase().endsWith("0a")) {
                endCode = endCode.substring(0, endCode.length() - 2);
                log("接收到udp1001数据去除0A：" + endCode);
            }
            writeData(endCode);
            mBinding.tvStartCollect.setText(R.string.start_collect);
            mBinding.tvStartCollect.setEnabled(true);
        } else if (requestCode == 1002) {
            isStartUdp = false;
            log("接收到udp数据1002：" + endCode);
            if (endCode.toLowerCase().endsWith("0a")) {
                endCode = endCode.substring(0, endCode.length() - 2);
                log("接收到udp1002数据去除0A：" + endCode);
            }
            writeHistoryData(endCode);
        } else {
            log("接收到udp数据1000：" + endCode);
        }
    }

    private Map<String, Integer> writeFailed = new HashMap<>();

    private void writeData(final String hex) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                BleManager.getInstance().write(
                        mBleDevice,
                        mWriteCharacteristic.getService().getUuid().toString(),
                        mWriteCharacteristic.getUuid().toString(),
                        HexUtil.hexStringToBytes(hex),
                        new BleWriteCallback() {

                            @Override
                            public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                                log("写入成功: " + HexUtil.formatHexString(justWrite, true));
                                writeFailed.remove(hex);
                            }

                            @Override
                            public void onWriteFailure(final BleException exception) {
                                log("写入异常：" + exception.getCode() + "------" + exception + "--" + hex + "--" + System.currentTimeMillis());
                                Integer count = writeFailed.putIfAbsent(hex, 0);
                                int c = count == null ? 0 : count;
                                if (c < 2) {
                                    log("重发：" + hex);
                                    writeFailed.put(hex, c + 1);
                                    writeData(hex);
                                } else {
                                    log("重发3次依然失败：" + hex);
                                    writeFailed.remove(hex);
                                }
                            }
                        });
            }
        }, 300);

    }

    private void writeHistoryData(final String hex) {
        BleManager.getInstance().write(
                mBleDevice,
                mWriteCharacteristic.getService().getUuid().toString(),
                mWriteCharacteristic.getUuid().toString(),
                HexUtil.hexStringToBytes(hex),
                new BleWriteCallback() {

                    @Override
                    public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                        log("写入成功: " + HexUtil.formatHexString(justWrite, true));
                        historyData.put(mEndData, hex);
                        if (stopUploadHistory != null) {
                            mHandler.removeCallbacks(stopUploadHistory);
                            stopUploadHistory = null;
                        }
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                log("resetClearHistory writeData---");
                                resetClearHistory();
                            }
                        }, 3000L);
                    }

                    @Override
                    public void onWriteFailure(final BleException exception) {
                        log("写入异常：" + exception.getCode() + "------" + exception + "--" + System.currentTimeMillis());
                        log("蓝牙写入失败了，重新开始接收1480");
                        if (stopUploadHistory != null) {
                            mHandler.removeCallbacks(stopUploadHistory);
                            stopUploadHistory = null;
                        }
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                resetClearHistory();
                            }
                        }, 3000L);
                    }
                });
    }

    /**
     * 开始接收蓝牙广播数据
     */
    private void startNotify() {
        if (mBleDevice == null || mConnectService == null || mNotifyCharacteristic == null) {
            Toast.makeText(this, "未找到Notify特征:0000ffa1-0000-1000-8000-00805f9b34fb", Toast.LENGTH_SHORT).show();
            return;
        }
        BleManager.getInstance().notify(
                mBleDevice,
                mConnectService.getUuid().toString(),
                mNotifyCharacteristic.getUuid().toString(),
                new BleNotifyCallback() {

                    @Override
                    public void onNotifySuccess() {
                        log("notify success");
                        //开始循环写入获取电流电压请求
                        startLoopWrite();
                    }

                    @Override
                    public void onNotifyFailure(final BleException exception) {
                        log("notify failure" + exception);
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
//                        log("接收到数据0000:" + HexUtil.formatHexString(data));
                        try {
                            if (isReceiveEndData && TextUtils.isEmpty(mEndData) && endSb.length() >= 260) {
                                if (endSb.length() > 260) {
                                    //数据不正确丢弃
                                    log("接收到1480数据不完整:" + mEndData);
                                    endSb = new StringBuffer();
                                    mEndData = "";
                                    isReceiveEndData = false;
                                } else {
                                    mEndData = endSb.toString();
                                    final String no = mEndData.substring(4, 12);
                                    final String rNo = mEndData.substring(12, 20);
                                    log("接收到1480数据完整:" + mEndData);
                                    log("接收到焊机编号：" + no + "，记录编号：" + rNo + "，时间：" + dateFormat.format(System.currentTimeMillis()));
                                    endCollect();
                                    return;
                                }

                            }
                            final String result = HexUtil.formatHexString(data);
                            if (result.startsWith("4154")) {
                                return;
                            }
                            if (result.startsWith("0103")) {
                                if (isReceiveEndData) {
                                    return;
                                }
                                log("接收到电流数据:" + result);
                                String voltage = result.substring(6, 10);
                                String electric = result.substring(10, 14);
                                final String time = dateFormat.format(System.currentTimeMillis());
                                final float v = Integer.parseInt(voltage, 16) * 0.1f;
                                final float e = Integer.parseInt(electric, 16) * 0.1f;
                                mRecords.add(new Record(v, e, time));
                                log("接收到电压:" + v + "，电流：" + e + "，时间：" + time);
                                showChartData(new ArrayList<>(mRecords.size() >= 20 ? mRecords.subList(mRecords.size() - 20, mRecords.size()) : mRecords));
                            } else if (result.startsWith("1480")) {
                                if (isReceiveEndData || writeCount > 0) {
                                    log("writeCount：" + writeCount);
                                    stopLoopWrite();
                                    return;
                                }
                                if (writeCount > -2) {
                                    //写入结束后的 前两条条1480不接收
                                    log("写入结束后的 前两条1480不接收");
                                    writeCount--;
                                    return;
                                }

                                if (TextUtils.isEmpty(mEndData)) {
                                    isReceiveEndData = true;
                                    if (endSb.length() == 0) {
                                        log("接收到1480头数据:" + result);
                                        endSb.append(result);
                                    }
                                }

                            } else {
                                if (isReceiveEndData && TextUtils.isEmpty(mEndData)) {
                                    if (endSb.length() < 260) {
                                        endSb.append(result);
                                        log("接收到1480尾数据:" + result);
                                    }
                                }
                            }
                        } catch (Exception e) {
                            log("接收到格式异常的数据：" + HexUtil.formatHexString(data));
                        }
                    }
                });
    }

    /**
     * 停止接收蓝牙广播数据
     */
    private void stopNotify() {
        if (mBleDevice == null || mConnectService == null || mNotifyCharacteristic == null) {
            return;
        }
        BleManager.getInstance().stopNotify(
                mBleDevice,
                mNotifyCharacteristic.getService().getUuid().toString(),
                mNotifyCharacteristic.getUuid().toString());
    }


    /**
     * 开始接收蓝牙广播数据
     */
    private void startClearHistoryNotify() {
        if (mBleDevice == null || mConnectService == null || mNotifyCharacteristic == null) {
            Toast.makeText(this, "未找到Notify特征:0000ffa1-0000-1000-8000-00805f9b34fb", Toast.LENGTH_SHORT).show();
            return;
        }
        BleManager.getInstance().notify(
                mBleDevice,
                mConnectService.getUuid().toString(),
                mNotifyCharacteristic.getUuid().toString(),
                clearNotifyCallback = new BleNotifyCallback() {

                    @Override
                    public void onNotifySuccess() {
                        log("hnotify success");
                        //开始循环写入获取电流电压请求
                    }

                    @Override
                    public void onNotifyFailure(final BleException exception) {
                        log("hnotify failure" + exception);
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
//                        log("接收到数据0000:" + HexUtil.formatHexString(data));
                        try {
                            final String result = HexUtil.formatHexString(data);
                            if (isUdpSending) {
                                return;
                            }
                            if (isReceiveEndData && TextUtils.isEmpty(mEndData) && endSb.length() >= 260) {
                                if (endSb.length() > 260) {
                                    //数据不正确丢弃
                                    log("h接收到1480数据不完整:" + mEndData);
                                    endSb = new StringBuffer();
                                    mEndData = "";
                                    isReceiveEndData = false;
                                } else {
                                    mEndData = endSb.toString();
                                    if (historyData.containsKey(mEndData)) {
                                        log("h接收到相同1480数据跳过");
                                        endSb = new StringBuffer();
                                        mEndData = "";
                                        isReceiveEndData = false;
                                    } else {
                                        final String no = mEndData.substring(4, 12);
                                        final String rNo = mEndData.substring(12, 20);
                                        log("h接收到1480数据完整:" + mEndData);
                                        log("h接收到焊机编号：" + no + "，记录编号：" + rNo + "，时间：" + dateFormat.format(System.currentTimeMillis()));
                                        endClearHistory();
                                    }
                                    return;
                                }

                            }
                            if (result.startsWith("4154")) {
                                return;
                            }
                            if (result.startsWith("0103")) {
                                if (isReceiveEndData) {
                                }
                            } else if (result.startsWith("1480")) {
                                if (isReceiveEndData) {
                                    return;
                                }
                                if (TextUtils.isEmpty(mEndData)) {
                                    isReceiveEndData = true;
                                    if (endSb.length() == 0) {
                                        log("h接收到1480头数据:" + result);
                                        endSb.append(result);
                                    }
                                }

                            } else {
                                if (isReceiveEndData && TextUtils.isEmpty(mEndData)) {
                                    if (endSb.length() < 260) {
                                        endSb.append(result);
                                        log("h接收到1480尾数据:" + result);
                                    }
                                }
                            }
                        } catch (Exception e) {
                            log("接收到格式异常的数据：" + HexUtil.formatHexString(data));
                        }
                    }
                });
    }

    Runnable stopUploadHistory = null;

    /**
     * 结束数据采集
     */
    private void endClearHistory() {
        stopNotify();
        isUdpSending = true;
        if (clearNotifyCallback != null) {
            clearNotifyCallback.getHandler().removeCallbacksAndMessages(null);
        }
        //UDP获取结束指令
        log("history udp send:" + mEndData);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                sendUdp(mEndData, 1002);
            }
        }, 2000L);
    }

    /**
     * 结束数据采集
     */
    private void endCollect() {
        log("采集结束~");
        stopLoopWrite();
        stopNotify();
        if (mRecords.size() > 0) {
            mBinding.tvCollectState.setText(R.string.uncollect);
        }
        showChartData(new ArrayList<Record>());
        //UDP获取结束指令
        log("udp send:" + mEndData);
        sendUdp(mEndData, 1001);
        uploadData();
    }

    private void sendUdp(final String endData, final int requestCode) {
        if (requestCode == 1001) {
            mBinding.tvStartCollect.setText(R.string.start_send_udp);
            mBinding.tvStartCollect.setEnabled(false);
        }
        isStartUdp = true;
        if (!UdpClient.getInstance().isConnect()) {
            connectUdp();
        }
        sendUdpService.submit(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    if (TextUtils.isEmpty(mEndData)) {
                        return;
                    }
                    if (!isStartUdp) {
                        return;
                    }
                    log("第" + (i + 1) + "次发送udp" + System.currentTimeMillis());
                    log("发送内容：" + endData);
                    UdpClient.getInstance().sendByteCmd(HexUtil.hexStringToBytes(endData), requestCode);
                    try {
                        Thread.sleep(2000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        log("5次发送udp都未能收到响应");
                        isStartUdp = false;
                        Toast.makeText(CollectActivity.this, "udp服务器异常请检查", Toast.LENGTH_SHORT).show();
                        if (requestCode == 1001) {
                            mBinding.tvStartCollect.setText(R.string.start_collect);
                            mBinding.tvStartCollect.setEnabled(true);
                        } else {
                            if (stopUploadHistory != null) {
                                mHandler.removeCallbacks(stopUploadHistory);
                                stopUploadHistory = null;
                            }
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    log("resetClearHistory send failed---");
                                    resetClearHistory();
                                }
                            }, 3000L);
                        }
                    }
                });
            }
        });

    }

    private void showChartData(List<Record> records) {
        if (records.isEmpty()) {
            records.add(new Record(0, 0, ""));
        }
        ArrayList<Entry> values1 = new ArrayList<>();
        ArrayList<Entry> values2 = new ArrayList<>();

        for (int i = 0; i < records.size(); i++) {
            Record record = records.get(i);
            float voltage = record.voltage;
            float electric = record.electric;
            values1.add(new Entry(i, voltage));
            values2.add(new Entry(i, electric));
        }

        LineDataSet set1, set2;

        if (mBinding.chart.getData() != null &&
                mBinding.chart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) mBinding.chart.getData().getDataSetByIndex(0);
            set2 = (LineDataSet) mBinding.chart.getData().getDataSetByIndex(1);
            set1.setValues(values1);
            set2.setValues(values2);
        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(values1, "电压");
            set1.setValueFormatter(new ValueFormatter() {
                @Override
                public String getFormattedValue(float value) {
                    return NumberFormat.getInstance().format(value);
                }
            });
            set1.setAxisDependency(YAxis.AxisDependency.LEFT);
            set1.setColor(ColorTemplate.getHoloBlue());
            set1.setCircleColor(Color.BLACK);
            set1.setLineWidth(2f);
            set1.setCircleRadius(3f);
            set1.setFillAlpha(65);
            set1.setFillColor(ColorTemplate.getHoloBlue());
            set1.setHighLightColor(Color.rgb(244, 117, 117));
            set1.setDrawCircleHole(false);
            set2 = new LineDataSet(values2, "电流");
            set2.setValueFormatter(new ValueFormatter() {
                @Override
                public String getFormattedValue(float value) {
                    return NumberFormat.getInstance().format(value);
                }
            });
            set2.setAxisDependency(YAxis.AxisDependency.RIGHT);
            set2.setColor(Color.RED);
            set2.setCircleColor(Color.BLACK);
            set2.setLineWidth(2f);
            set2.setCircleRadius(3f);
            set2.setFillAlpha(65);
            set2.setFillColor(Color.RED);
            set2.setDrawCircleHole(false);
            set2.setHighLightColor(Color.rgb(244, 117, 117));

            // create a data object with the data sets
            LineData data = new LineData(set1, set2);
            data.setValueTextColor(Color.BLACK);
            data.setValueTextSize(9f);

            // set data
            mBinding.chart.setData(data);
        }
        mBinding.chart.getData().notifyDataChanged();
        mBinding.chart.notifyDataSetChanged();
        mBinding.chart.invalidate();
    }

    /**
     * 上传数据到服务
     */
    private void uploadData() {
        if (mRecords.isEmpty()) {
            return;
        }
        showProgress("正在上传数据...");
        uploadService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Gson gson = new Gson();
//                    String json = gson.toJson(mRecords);
//                    final String rNo = mEndData.substring(12, 20);
                    final String no = mEndData.substring(4, 12);
                    final String rNo = mEndData.substring(12, 20);
//                    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
                    String fileName = Integer.parseInt(no, 16) + "-" + Integer.parseInt(rNo, 16) + ".txt";
                    File cacheFile = new File(getCacheDir(), fileName);
                    if (cacheFile.exists()) {
                        cacheFile.delete();
                    }
                    OutputStreamWriter bfw = new OutputStreamWriter(new FileOutputStream(cacheFile, true), StandardCharsets.UTF_8);
                    DecimalFormat decimalFormat = new DecimalFormat("0000");
                    for (int i = 0; i < mRecords.size(); i++) {
                        Record record = mRecords.get(i);
                        if (record.voltage < 5) {
                            continue;
                        }
                        float v = record.electric * record.voltage;
                        bfw.write(decimalFormat.format(i + 1) + "," + Math.round(v));
                        bfw.write(System.getProperty("line.separator"));
                    }
                    bfw.flush();
                    bfw.close();
                    RequestBody body = new MultipartBody.Builder()
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("file", fileName, RequestBody.create(MediaType.parse("application/octet-stream"), cacheFile))
                            .build();

                    Request request = new Request.Builder()
                            .url(AppConstant.getFileUrl() + "FileUpload")
                            .post(body)
                            .build();
                    OkHttpClient client = new OkHttpClient();
                    final Response response = client.newCall(request).execute();
                    if (response.code() == 200) {
                        //上传成功
                        String resultJson = response.body().string();
                        final Result<String> result = gson.fromJson(resultJson, new TypeToken<Result<String>>() {
                        }.getType());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (result.code == 200) {
                                    Toast.makeText(CollectActivity.this, "数据上传成功", Toast.LENGTH_SHORT).show();
                                    log("数据上传成功");
                                } else {
                                    Toast.makeText(CollectActivity.this, "数据上传失败，" + result.info, Toast.LENGTH_SHORT).show();
                                    log("数据上传失败，" + result.info);
                                }
                                hideProgress();
                            }
                        });
                        uploadLocation(rNo, no, AppConstant.mLatitude, AppConstant.mLongitude);
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(CollectActivity.this, "数据上传失败，" + response.code(), Toast.LENGTH_SHORT).show();
                                log("数据上传失败，" + response.code());
                                hideProgress();
                            }
                        });
                    }
                } catch (final IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(CollectActivity.this, "数据上传失败，" + e, Toast.LENGTH_SHORT).show();
                            log("数据上传失败，" + e);
                            hideProgress();
                        }
                    });
                }

            }
        });
    }

    /**
     * 上传定位位置
     *
     * @param rNo       记录号
     * @param no        设备号
     * @param latitude  纬度
     * @param longitude 经度
     */
    private void uploadLocation(String rNo, String no, double latitude, double longitude) {
        Map<String, Object> params = new HashMap<>();
        params.put("F_RecordNum", Integer.parseInt(rNo, 16));
        params.put("F_MachineCode", Integer.parseInt(no, 16));
        params.put("F_Latitude", latitude);
        params.put("F_Longitude", longitude);
        log("上传经纬度-->" + new Gson().toJson(params));
        RetrofitManager.getApi().updateButtRecord(params)
                .compose(new BaseEmptyTransformer<>())
                .subscribe(new DisposableObserver<Result<Object>>() {
                    @Override
                    public void onNext(Result<Object> objectResult) {
                        log("上传经纬度成功-->");
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        log("上传经纬度接口异常：" + e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private String getLineContent(int count, Record record) {
//        if (String.valueOf())
        return "";
    }

    private void showProgress(String content) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
        }
        mProgressDialog.setMessage(content);
        mProgressDialog.show();
    }

    private void hideProgress() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.cancel();
        }
    }

    private void showClearProgress(String content) {
        if (mUploadProgressDialog == null) {
            mUploadProgressDialog = new ProgressDialog(this);
            mUploadProgressDialog.setCancelable(true);
            mUploadProgressDialog.setCanceledOnTouchOutside(true);
        }
        mUploadProgressDialog.setMessage(content);
        mUploadProgressDialog.show();
        Window window = mUploadProgressDialog.getWindow();
        if (window != null) {
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    }

    private void hideClearProgress() {
        if (mUploadProgressDialog != null) {
            Window window = mUploadProgressDialog.getWindow();
            if (window != null) {
                window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            }
            mUploadProgressDialog.cancel();
        }
    }

    private void log(final String content) {
        mBinding.tvLog.post(new Runnable() {
            @Override
            public void run() {
                mBinding.tvLog.append(content);
                mBinding.tvLog.append("\n");
                mBinding.svLog.fullScroll(View.FOCUS_DOWN);
            }
        });
    }

    private String getServiceUUID(BleDevice bleDevice) {
        return bleDevice.getName().toUpperCase().startsWith("HC") ? "0000ffe0-0000-1000-8000-00805f9b34fb" : "0000ffa0-0000-1000-8000-00805f9b34fb";
    }

    private String getNotifyUUID(BleDevice bleDevice) {
        return bleDevice.getName().toUpperCase().startsWith("HC") ? "0000ffe1-0000-1000-8000-00805f9b34fb" : "0000ffa1-0000-1000-8000-00805f9b34fb";
    }

    private String getWriteUUID(BleDevice bleDevice) {
        boolean isFFE1 = bleDevice.getName().contains("04") || bleDevice.getName().contains("08");
        return bleDevice.getName().toUpperCase().startsWith("HC") ? (isFFE1 ? "0000ffe1-0000-1000-8000-00805f9b34fb" : "0000ffe2-0000-1000-8000-00805f9b34fb") : "0000ffa1-0000-1000-8000-00805f9b34fb";
    }


    @Override
    public final void onRequestPermissionsResult(int requestCode,
                                                 @NonNull String[] permissions,
                                                 @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_PERMISSION_LOCATION:
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                            onPermissionGranted(permissions[i]);
                        }
                    }
                }
                break;
        }
    }

    private void checkPermissions() {
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                onPermissionGranted(permission);
            } else {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
        }
    }

    private void onPermissionGranted(String permission) {
        switch (permission) {
            case Manifest.permission.ACCESS_COARSE_LOCATION:
                break;
            case Manifest.permission.ACCESS_FINE_LOCATION:
                if (!checkGPSIsOpen()) {
                    new AlertDialog.Builder(this)
                            .setTitle(R.string.notifyTitle)
                            .setMessage(R.string.gpsNotifyMsg)
                            .setNegativeButton(R.string.cancel,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            finish();
                                        }
                                    })
                            .setPositiveButton(R.string.setting,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                            startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
                                        }
                                    })

                            .setCancelable(false)
                            .show();
                } else {
                    getLocation();
                }
                break;
        }
    }

    private void getLocation() {
        mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (mLocationManager != null) {
            if (!GpsUtil.isGpsOpen(this)) {
                log("手机gps开关未打开");
                return;
            }
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "未获得定位权限", Toast.LENGTH_SHORT).show();
                log("未获得定位权限");
                return;
            }
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 10, locationListener);
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 10, locationListener);
        }
    }


    private boolean checkGPSIsOpen() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null)
            return false;
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }
}
